/**
 * \file NotificationManager.cpp
 * \brief NotificationManager declaration class.
 * \author Edouard ROGE
 * \date 10 august 2012
 */

#include <algorithm>
#include "NotificationHandler.h"
#include "NotificationManager.h"

namespace Core
{
	namespace Notification
	{
		NotificationManager::NotificationManager()
		{
			m_pActiveObject = ActiveObject::CreateActiveObject();
		}

		NotificationManager::~NotificationManager()
		{
		}

		void NotificationManager::Register(NotificationHandler * _pHandler, const NotificationType & _type)
		{
			std::lock_guard<std::mutex> lock(m_mutex);
			m_pHandlers[_type].push_back(_pHandler);
		}

		void NotificationManager::Unregister(NotificationHandler * _pHandler, const NotificationType & _type)
		{
			std::lock_guard<std::mutex> lock(m_mutex);
			auto it = std::find(std::begin(m_pHandlers[_type]), std::end(m_pHandlers[_type]), _pHandler);
			if (it != std::end(m_pHandlers[_type]))
			{
				m_pHandlers[_type].erase(it);
			}
		}

		void NotificationManager::Notify(const Notification & _notification)
		{
			m_pActiveObject->Send(std::bind(&NotificationManager::NotifyHandlers, this, _notification));
		}

		void NotificationManager::NotifyHandlers(Notification _notification)
		{
			for (auto it = std::begin(m_pHandlers[_notification.GetType()]); it != std::end(m_pHandlers[_notification.GetType()]); ++it)
			{
				(*it)->Handle(_notification);
			}
		}
	}
}